
/*****************************************************************************
 * File: Server.java
 * Author:  Todd Silvia & Phil Pilosi
 * Class:   CS 441 - Spring 2011
 * Project: 2 - Distributed Booking Agent, with RMI
 * Date:    February 28th 2011
 * Description: <Insert Description Here>
 */

import java.io.*;
import java.util.*;
import java.rmi.*;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.ObjectOutputStream;
import java.io.IOException;


public class Server  
{
	InputStreamReader inStream;
	BufferedReader userInput;
	ArrayList<Event> database;
	FileInputStream  fileIn;
	ObjectInputStream objectIn;
	String curDir;

	public Server()
	{
		inStream = new InputStreamReader(System.in);
		userInput = new BufferedReader(inStream);
		database = new ArrayList<Event>();
		fileIn = null;
		objectIn = null;
		curDir = System.getProperty("user.dir");
	}

	public void newMain(String[] args) throws IOException, ClassNotFoundException
	{
		boolean firstFound = false;
		boolean secondFound = false;
		File dir = new File(curDir);

		String[] children = dir.list();
		if (children == null) {
			System.out.println("Does not exist or is not a directory!");
		    // Either dir does not exist or is not a directory
		} else {
		    for (int i=0; i<children.length; i++) {
		        // Get filename of file or directory
		        String filename = children[i];
		        if(filename.compareToIgnoreCase("database1.txt") == 0) {
		        	File test1 = new File("database1.txt");
		        	if(test1.canRead()) {
		        		firstFound = true;
		        	}
		        }
		        if(filename.compareTo("database2.txt") == 0) {
		        	File test2 = new File("database2.txt");
		        	if(test2.canRead()) {
		        		secondFound = true;
		        	}
		        }
		    }
		}
		
		if((firstFound == true)&&(secondFound == false)) {
			//load first
			System.out.println("Only found file ONE");
			fileIn = new FileInputStream("database1.txt");
			objectIn = new ObjectInputStream(fileIn);
			database = (ArrayList<Event>)objectIn.readObject();
			
		}else if((firstFound == false)&&(secondFound == true)) {
			//load second
			System.out.println("Only found file 2");
			fileIn = new FileInputStream("database2.txt");
			objectIn = new ObjectInputStream(fileIn);
			database = (ArrayList<Event>)objectIn.readObject();
			
		}else if((firstFound == true)&&(secondFound == true)) {
			//Find out which one to load
			System.out.println("Found both files!");
			File fileOne = new File("database1.txt");
			File fileTwo = new File("database2.txt");
			
			if(fileOne.lastModified() < fileTwo.lastModified()) {
				fileIn = new FileInputStream("database2.txt");
				objectIn = new ObjectInputStream(fileIn);
				database = (ArrayList<Event>)objectIn.readObject();
			} else {
				fileIn = new FileInputStream("database1.txt");
				objectIn = new ObjectInputStream(fileIn);
				database = (ArrayList<Event>)objectIn.readObject();
			}
		}else {
			System.out.println("No save file found starting brand new data server!");
		}
		
		try {
			/*if(args.length == 1)
			{
				List temp = null;
				fileIn = new FileInputStream(args[0]);
				objectIn = new ObjectInputStream(fileIn);
				System.out.println("File name found: " + args[0]);
				database = (ArrayList<Event>)objectIn.readObject();
			}*/
			//else
			//{
			//	List temp = null;
			//	fileIn = new FileInputStream("database.txt");
			//	objectIn = new ObjectInputStream(fileIn);
			//	database = (ArrayList<Event>)objectIn.readObject();
			//}
			System.out.println("Server starting up!");

			this.startRegistry(13337);

			ServerFunc trial1 = new ServerImp(database); //Need to change variable name.

			Naming.rebind("rmi://localhost:13337/dataServer", trial1);

			System.out.println("Server is now running");
		}
		catch(Exception e)
		{
			System.out.println("Error: " + e);
		}


	}

	public static void main(String[] args)
	{
		Server newServer = new Server();
		try {
			newServer.newMain(args);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}

	//Use this to add the stub to the local registry that is created by the port number passed
	//in as a parameter.	
    private static void startRegistry(int RMIPortNum)
       throws RemoteException{
    	try 
		{
      		Registry registry = 
	        LocateRegistry.getRegistry(RMIPortNum);
	        registry.list( );  
      	    // This call will throw an exception
            // if the registry does not already exist
    	}
    	catch (RemoteException e) 
		{ 
      		// No valid registry at that port.
     	    Registry registry = 
       	    LocateRegistry.createRegistry(RMIPortNum);
    	}
  } // end startRegistry

}

